package com.github.defense.plugin.gray.netflix.hystrix;

import com.github.defense.plugin.gray.context.GrayLocalContext;
import com.github.defense.plugin.gray.request.GrayRequest;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableDefault;

/**
 * @Author: lettger
 * @Date: 2021/6/18 2:14 下午
 */
public class HystrixLocalContext implements GrayLocalContext {

    public static final HystrixRequestVariableDefault<GrayRequest> hystrix = new HystrixRequestVariableDefault<>();


    @Override
    public void setGrayRequest(GrayRequest request) {
        initServiceContext();
        hystrix.set(request);
    }

    @Override
    public GrayRequest getGrayRequest() {
        initServiceContext();
        return hystrix.get();
    }

    @Override
    public void removeLocalContext() {
        if (HystrixRequestContext.isCurrentThreadInitialized()) {
            HystrixRequestContext.getContextForCurrentThread().shutdown();
        }
    }

    private static void initServiceContext() {
        if (!HystrixRequestContext.isCurrentThreadInitialized()) {
            HystrixRequestContext.initializeContext();
        }
    }
}
